<?php
/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

define( '_JEXEC', 1 );
require_once './classes/FCRegistration.php';
require_once ('./classes/FCUtils.php');

define( 'DS', DIRECTORY_SEPARATOR );

$_file_ = str_replace(constant('DS').'modules'.constant('DS').'mod_friendconnect', '', dirname(__FILE__));
define('JPATH_BASE',  $_file_);

chdir('../../');
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'application'.DS.'module'.DS.'helper.php' );
include_once (JPATH_BASE .DS.'components'.DS.'com_user'.DS.'controller.php');
include_once (JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'base'.DS.'observable.php');
$config =& JFactory::getConfig();
$config->setValue('config.absolute_path', JPATH_BASE);

$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();
$db = & JFactory::getDBO();
$user = & JFactory::getUser();
JPluginHelper::importPlugin('system');

$module = JModuleHelper::getModule('friendconnect', '');
$params = array();
$params_lines = explode("\n",$module->params);
foreach($params_lines as $line) {
  $pair = explode("=",$line);
  $params[$pair[0]] = $pair[1];
}

$site_id = trim($params['fc_site_id']);


$fcauth_token = FCUtils::getFCAuthToken($site_id);
$viewer = FCUtils::getViewer($fcauth_token);

if(!$viewer) {
  header('Location: '.str_replace('modules/mod_friendconnect/', '', JURI::base()));
}

$db->setQuery("SELECT u.id, u.username, u.email FROM #__users AS u INNER JOIN #__friendconnect AS fc ON u.id=fc.uid WHERE fc.fcid = ".$db->Quote($viewer->id));
$user_data = $db->loadObject();
if(!$user_data) { // the user is not in the database
  if($user->id) { 
    // the user is logged in with his joomla account update  
    // link his joomla account with his friendconnect account
    $username = $user->username;
    $user_id = $user->id;
  } else {
    // create the user
    //generate an unique username
    $i = 0;
    $username_base = str_replace(' ', '_', $viewer->displayName);
    $username = '';
    do {
      if (!$username) {
        $username = $username_base; 
      } else { 
        $username = $username_base.$i; 
      }
      $db->setQuery("SELECT id FROM #__users WHERE username = ".$db->Quote($username));
      $data = $db->loadObject();
      $i++;
    }while($data);
    $user_details['username'] = $username;
    $user_details['password'] = substr(uniqid(true), 0, 20);
    $user_details['email'] = $viewer->id.'@google.friendconnect.com';
    $user_id = FCRegistration::register($user_details, $viewer);
  }
  if ($user_id) {
    $query = 'INSERT INTO #__friendconnect (uid, fcid) VALUES('.$db->Quote($user_id).', '.$db->Quote($viewer->id).')';
    $db->setQuery($query);
    $db->query();
  }
} else {
  $username = $user_data->username;
}

//sign in an existing user
jimport('joomla.user.authentication');
JPluginHelper::importPlugin('user');
$authenticate = & JAuthentication::getInstance(); //though we don't use this object here, creating it somehow makes JAuthenticationResponse class available
$authenticate_response = new JAuthenticationResponse();
$authenticate_response->status = JAUTHENTICATE_STATUS_SUCCESS;
//to make everything run fine, we need only username
$authenticate_response->username = $username;
$results = $mainframe->triggerEvent('onLoginUser', array((array)$authenticate_response));
header('Location: '.str_replace('modules/mod_friendconnect/', '', JURI::base()));
